import editForm from "../form/form.vue";
import changeForm from "../form/changePassForm.vue";
import resetForm from "../form/resetForm.vue";
import { message } from "@/utils/message";
import { transformI18n } from "@/plugins/i18n";
import { addDialog } from "@/components/ReDialog";
import type {
  changePassProps,
  FormItemProps,
  resetPassProps
} from "../utils/types";
import type { PaginationProps } from "@pureadmin/table";
import { deviceDetection } from "@pureadmin/utils";
import { Md5 } from "ts-md5";
import AES from "./aes.js";
import {
  getAllUesrList,
  addUser,
  deleteCurrentUser,
  updateUser,
  changePassword,
  resetPassword
} from "@/api/user";

import {
  type Ref,
  reactive,
  ref,
  onMounted,
  h,
  toRaw,
  watch,
  computed
} from "vue";

// refreshCallback?: () => void
export function useRole(tableRef: Ref, treeRef: Ref) {
  const form = reactive({
    customerName: "",
    shortName: "",
    mobile: "",
    remark: ""
  });

  const curRow = ref();
  const formRef = ref();
  const dataList = ref([]);
  const allCustomer = ref([]);
  const treeIds = ref([]);
  const treeData = ref([]);
  const isShow = ref(false);
  const loading = ref(false);
  const isLinkage = ref(false);
  const treeSearchValue = ref();
  const isExpandAll = ref(false);
  const isSelectAll = ref(false);
  const selectedNum = ref(0);
  const treeProps = {
    value: "id",
    label: "title",
    children: "children"
  };
  const pag = reactive({
    customerId: "",
    pageSize: 20,
    page: 1
  });
  const pagination = reactive<PaginationProps>({
    pageSize: 20,
    currentPage: 1,
    total: 0
  });
  const columns: TableColumnList = [
    {
      label: "id",
      prop: "id",
      width: 80
    },
    {
      label: "客户名",
      prop: "userName",
      minWidth: 80
    },
    {
      label: "账号状态",
      prop: "userState",
      minWidth: 80,
      cellRenderer: scope => {
        const text = scope.row.userState ? "启用" : "关闭";
        return h("span", text);
      }
    },
    {
      label: "手机号",
      prop: "mobile",
      minWidth: 80,
      cellRenderer: scope => {
        const text = scope.row.mobile ? scope.row.mobile : "暂无";
        return h("span", text);
      }
    },
    {
      label: "操作",
      fixed: "right",
      minWidth: 330,
      slot: "operation"
    }
  ];

  const buttonClass = computed(() => {
    return [
      "!h-[20px]",
      "reset-margin",
      "!text-gray-500",
      "dark:!text-white",
      "dark:hover:!text-primary"
    ];
  });

  // 删除当前的用户
  async function handleDelete(row) {
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    await deleteCurrentUser({ id: toRaw(row.id) });
    message(`您删除了一条用户数据`, {
      type: "success"
    });
    onSearch();
  }
  // 切换size大小
  async function handleSizeChange(val: number) {
    loading.value = true;
    pag.pageSize = val;
    const { data } = await getAllUesrList(toRaw(pag));
    dataList.value = data;
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }
  // 切换当前页
  async function handleCurrentChange(val: number) {
    loading.value = true;
    pag.page = val;
    // const { data } = await getAllUesrList(toRaw(pag));
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }
  // 拿所有的用户
  async function onSearch() {
    loading.value = true;
    setTimeout(() => {
      loading.value = false;
    }, 500);
    const { data } = await getAllUesrList(toRaw(pag));
    dataList.value = data;
  }

  const resetForm1 = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };
  // 新增 / 修改 用户的弹框
  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}用户`,
      props: {
        formInline: {
          id: row?.id ?? "",
          userName: row?.userName ?? "",
          mobile: row?.mobile ?? "",
          userPass: row?.userPass ?? "",
          userState: true
        }
      },
      width: "40%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了一条用户数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(async valid => {
          if (valid) {
            // 表单规则校验通过
            if (title === "新增") {
              const addData = { ...curData };
              addData.userPass = AES.encrypt(addData.userPass); //加密
              addData.userState = addData.userState ? 1 : 0; //加密
              await addUser(toRaw(addData));
              chores();
            } else {
              const addData = { ...curData };
              addData.userPass = AES.encrypt(addData.userPass); //加密
              addData.userState = addData.userState ? 1 : 0; //加密
              await updateUser(toRaw(addData));
              chores();
            }
          }
        });
      }
    });
  }
  // 重置密码的弹框
  function resetDialog(row?: resetPassProps) {
    addDialog({
      title: `重置用户密码`,
      props: {
        formInline: {
          id: row?.id ?? "",
          userPass: row?.userPass ?? ""
        }
      },
      width: "40%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(resetForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as resetPassProps;
        function chores() {
          message(`密码已重置!`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(async valid => {
          if (valid) {
            // 表单规则校验通过
            const addData = { ...curData };
            addData.userPass = AES.encrypt(addData.userPass); //加密
            await resetPassword(toRaw(addData));
            chores();
          }
        });
      }
    });
  }
  // 修改 用户的密码
  function changeDialog(title = "新增") {
    addDialog({
      title: `修改密码`,
      props: {
        formInline: {
          id: localStorage.getItem("userId"),
          password: "",
          oldPassword: "",
          newPassword: ""
        }
      },
      width: "40%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(changeForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as changePassProps;
        function chores() {
          message(`您修改了密码`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(async valid => {
          if (valid) {
            // 表单规则校验通过
            if (title === "新增") {
              await changePassword(toRaw(curData));
              chores();
            } else {
              const md5 = new Md5();
              const updatedData = { ...curData };
              if (updatedData.password !== updatedData.newPassword) {
                message(`两次密码输入不一致`, {
                  type: "error"
                });
                return;
              }
              md5.appendAsciiStr(updatedData.oldPassword);
              updatedData.oldPassword = md5.end().toString().toUpperCase();
              updatedData.newPassword = AES.encrypt(updatedData.newPassword); //加密
              await changePassword(toRaw(updatedData));
              chores();
              done(); // 关闭弹框
            }
          }
        });
      }
    });
  }
  // 点击列表后面的下拉按钮
  function handleUpdate(row) {
    console.log(row);
  }

  const filterMethod = (query: string, node) => {
    return transformI18n(node.title)!.includes(query);
  };

  onMounted(async () => {
    // onSearch();
  });

  watch(isExpandAll, val => {
    val
      ? treeRef.value.setExpandedKeys(treeIds.value)
      : treeRef.value.setExpandedKeys([]);
  });

  watch(isSelectAll, val => {
    val
      ? treeRef.value.setCheckedKeys(treeIds.value)
      : treeRef.value.setCheckedKeys([]);
  });

  return {
    pag,
    form,
    isShow,
    curRow,
    loading,
    columns,
    dataList,
    treeData,
    selectedNum,
    treeProps,
    isLinkage,
    pagination,
    isExpandAll,
    isSelectAll,
    treeSearchValue,
    buttonClass,
    onSearch,
    resetForm1,
    openDialog,
    changeDialog,
    handleDelete,
    filterMethod,
    transformI18n,
    handleSizeChange,
    handleCurrentChange,
    handleUpdate,
    allCustomer,
    resetDialog
  };
}
